<?php
class ApiController extends Controller {
   Const APPLICATION_ID = 'ASCCPE';
 
   private $format = 'json';
  
   private function _sendResponse($status = 200, $body = '', $content_type = 'text/html') {
      header("Access-Control-Allow-Origin: *");
      header("Access-Control-Allow-Headers: Authorization");
      $status_header = 'HTTP/1.1 ' . $status . ' ' . $this->_getStatusCodeMessage($status);
      header($status_header);
      header('Content-type: ' . $content_type);
   
      if($body != '') {
        echo $body;
        exit;
     }
     else {
        $message = '';
        switch($status) {
           case 401:
              $message = 'You must be authorized to view this page.';
              break;
           case 404:
              $message = 'The requested URL ' . $_SERVER['REQUEST_URI'] . ' was not found.';
              break;
           case 500:
              $message = 'The server encountered an error processing your request.';
              break;
           case 501:
              $message = 'The requested method is not implemented.';
              break;
           }
        $signature = ($_SERVER['SERVER_SIGNATURE'] == '') ? $_SERVER['SERVER_SOFTWARE'] . ' Server at ' . $_SERVER['SERVER_NAME'] . ' Port ' . $_SERVER['SERVER_PORT'] : $_SERVER['SERVER_SIGNATURE'];
        $body = '
        <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
        <html>
        <head>
           <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
           <title>' . $status . ' ' . $this->_getStatusCodeMessage($status) . '</title>
        </head>
        <body>
           <h1>' . $this->_getStatusCodeMessage($status) . '</h1>
           <p>' . $message . '</p>
           <hr />
           <address>' . $signature . '</address>
        </body>
        </html>';
        echo $body;
        exit;
      }
   }
   private function _getStatusCodeMessage($status) {
      $codes = Array(
         200 => 'OK',
         400 => 'Bad Request',
         401 => 'Unauthorized',
         402 => 'Payment Required',
         403 => 'Forbidden',
         404 => 'Not Found',
         500 => 'Internal Server Error',
         501 => 'Not Implemented',
      );
      return (isset($codes[$status])) ? $codes[$status] : '';
   }
   public function actionPreflight() {
      $content_type = 'application/json';
      $status = 200;
      $status_header = 'HTTP/1.1 ' . $status . ' ' . $this->_getStatusCodeMessage($status);
      header($status_header);
      header("Access-Control-Allow-Origin: *");
      header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE");
      header("Access-Control-Allow-Headers: Authorization");
      header('Content-type: ' . $content_type);
   }
   public function actionCreate() {
      switch ($_GET['model']) {
         case 'axe':
            $post = file_get_contents("php://input");
            $values = json_decode($post, true);
            $defaults = array('parent' => null);
            $values = array_merge($defaults, $values);
            $node = new Axe;
            $node->name   = $values['name'];
            $node->parent = $values['parent'];
            if ($node->_save()) {
               $this->_sendResponse(200, CJSON::encode($node));
            }
            else {
               $this->_sendResponse(500, '');
            }
         break;
         case 'value':
            $post = file_get_contents("php://input");
            var_dump($post);
            die;
            $values = json_decode($post, true);
            $defaults = array('data' => null);
            $values = array_merge($defaults, $values);
            $node = new Value;
            $node->data = $values['data'];
            
         break;
      }
   }   
   public function actionList() {
      switch ($_GET['model']) {
         case 'axe':
            $query = null;
            $order = null;
            if (isset($_GET['query'])) $query = $_GET['query'];
            if (isset($_GET['order'])) $order = $_GET['order'];
            $results  = Axe::model()->_list($query, $order);
            try {
               $data = array();
               if ($results) {
                  $i = 0;
                  foreach ($results as $result) {
                     $data[$i]['id'] = $result->id;
                     $data[$i]['name'] = $result->name;
                     $data[$i]['fullname'] = $result->fullname;
                     $data[$i]['fullpath'] = $result->fullpath;
                     $data[$i]['level'] = $result->level;
                     $i++;
                  }
               }
               $this->_sendResponse(200, CJSON::encode($data));
            }
            catch (Exception $e) {
               $this->_sendResponse(500, '');
            }
         break;
      }
   }
   public function actionView() {
      switch ($_GET['model']) {
         case 'axe':
            $results  = Axe::model()->_view($_GET['id']);
            try {
               if ($results) {
                  $this->_sendResponse(200, CJSON::encode($results));
               }
               
            }
            catch (Exception $e) {
               $this->_sendResponse(500, '');
            }
         break;
      }
   }
   public function actionDelete() {
      switch ($_GET['model']) {
         case 'axe':
            if (isset($_GET['id'])) {
               try {
                 $node = Axe::model()->findByPk($_GET['id']);
                 if ($node) {
                     try {
                        $node->_delete();
                        $this->_sendResponse(200, '');
                     }
                     catch (Exception $e) {
                        $this->_sendResponse(500, '');
                     }
                  }
                  else {
                     $this->_sendResponse(500, '');
                  }
               }
               catch (Exception $e) {
                  $this->_sendResponse(500, '');
               }
            }
            else {
               $this->_sendResponse(400, '');
            }
         break;
      }
   }
   public function actionDeleteAll() {
      switch ($_GET['model']) {
         case 'axe':
            if (Axe::model()->_deleteAll()) {
               $this->_sendResponse(400, '');
            }
            else {
               $this->_sendResponse(500, '');
            }
         break;
      }
   }
   public function actionUpdate() {
      switch ($_GET['model']) {
         case 'axe':
            $post = file_get_contents("php://input");
            $values = json_decode($post, true);
            $axe = Axe::model()->findByPk($_GET['id']);
            if ($axe) {
               $axe->name = $values['name'];
               $axe->parent = $values['parent'];
               $axe = $axe->_update();
               if ($axe) {
                  $this->_sendResponse(200, CJSON::encode($axe));
               }
               else {
                  $this->_sendResponse(500, 'No item found');
               }
            }
            else {
               $this->_sendResponse(500, '');
            }
         break;
      }
   }   
}
?>